
// 前端app配置表

package misc

import (
	//"fmt"
	"errors"
	"strings"
	"time"
	"dhfshop/models"
	"dhfshop/models/consts"
	//"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
)

type WxAppCfg struct {
	WxAppCfgId   int64      `orm:"column(wxapp_cfg_id);pk;auto" json:"wxapp_cfg_id" form:"wxapp_cfg_id"`  //自增Id
	PartnerId    int64        `orm:"column(partner_id);index" json:"partner_id" form:"partner_id"` //文件的父ID
	StoreId      int64        `orm:"column(store_id)" json:"store_id" form:"store_id"`       //门店
	AppId        string     `orm:"column(app_id);size(32)" json:"app_id" form:"app_id"`       //微信ID
	Types        string     `orm:"column(types);size(24)" json:"types" form:"types"`       //类型
    Name         string     `orm:"column(name);size(40)" json:"name" form:"name"`            //键名
	Value        string     `orm:"column(value);type(text)" json:"value" form:"value"`     //值
	CreatedAt    time.Time  `orm:"column(created_at);auto_now_add;type(datetime)" json:"-"`
	CreatedAtStr string     `orm:"-" json:"created_at"`
	UpdatedAt    time.Time  `orm:"column(updated_at);auto_now;type(datetime)" json:"-"`
	UpdatedAtStr string     `orm:"-" json:"updated_at"`
	Note         string     `orm:"column(note);size(1024);null" json:"note" form:"note"`   //备注
}

func (u *WxAppCfg) TableUnique() [][]string {
	return [][]string{
		[]string{"StoreId", "AppId", "Name"},
	}
}

func init() {
	orm.RegisterModel(new(WxAppCfg))
}

func CreateWxAppCfg(appcfg *WxAppCfg) (id int64, err error) {
	o := models.GetDefaultDB()
	id, err = o.Insert(appcfg)
	return
}

func GetWxAppCfgByAppId(appId string) (appcfg *WxAppCfg, err error) {
	o := models.GetDefaultDB()
	appcfg = &WxAppCfg{AppId: appId}
	if err = o.Read(appcfg, "AppId"); err != nil {
		return
	}
	appcfg.UpdatedAtStr = appcfg.UpdatedAt.Format(consts.DATETIME_FORMAT)
	return
}

func GetWxAppCfgByAppIdAndName(appId, name string) (appcfg *WxAppCfg, err error) {
	o := models.GetDefaultDB()
	appcfg = &WxAppCfg{AppId: appId, Name:name}
	if err = o.Read(appcfg, "AppId", "Name"); err != nil {
		return
	}
	appcfg.UpdatedAtStr = appcfg.UpdatedAt.Format(consts.DATETIME_FORMAT)
	return
}

func GetWxAppCfgByAppIdAndNameAndStoreId(appId,name string,storeId int64) (appcfg *WxAppCfg, err error) {
	o := models.GetDefaultDB()
	appcfg = &WxAppCfg{AppId:appId,Name:name,StoreId:storeId}
	if err = o.Read(appcfg, "AppId", "Name", "StoreId"); err != nil {
		return
	}
	appcfg.UpdatedAtStr = appcfg.UpdatedAt.Format(consts.DATETIME_FORMAT)
	return
}

func GetAllWxAppCfgs(storeIds []int64,query map[string]string,fields []string,order_by map[string]string,offset int,limit int)([]*WxAppCfg, int64,error) {
	o := models.GetDefaultDB()
	qs := o.QueryTable(new(WxAppCfg))
	if start, ok := query["start_created"]; ok {
		if startTime, err := time.Parse(consts.DATELINKTIME_FORMAT, start); err == nil {
		    qs = qs.Filter("created_at__gte", startTime)
		}
		delete(query, "start_created")
	}
	if end, ok := query["end_created"]; ok {
		if endTime, err := time.Parse(consts.DATELINKTIME_FORMAT, end); err == nil {
	        qs = qs.Filter("created_at__lte", endTime)
	    }
		delete(query, "end_created")
	}
	for k, v := range query {
		k = strings.Replace(k, ".", "__", -1)
		if ok := strings.Contains(v, "|"); ok {
		    valueArr := strings.Split(v, "|")
			qs = qs.Filter(k, valueArr)
		}else{
		    qs = qs.Filter(k, v)
		}	
	}
	if len(storeIds) > 0 {
        qs = qs.Filter("store_id__in", storeIds)
    }
	cnt, err := qs.Count()
	var sortFields []string
	for k, v := range order_by {
		orderby := ""
		if v == "desc" {
			orderby = "-" + k
		} else if v == "asc" {
			orderby = k
		} else {
			return nil, 0, errors.New("Error: Invalid order. Must be either [asc|desc]")
		}
		sortFields = append(sortFields, orderby)
	}
	qs = qs.OrderBy(sortFields...)
	var lists []*WxAppCfg
	if _, err = qs.Limit(limit, offset).All(&lists, fields...); err == nil {
		for _, cfg := range lists {
			cfg.CreatedAtStr = cfg.CreatedAt.Format(consts.DATETIME_FORMAT)
            cfg.UpdatedAtStr = cfg.UpdatedAt.Format(consts.DATETIME_FORMAT)
	    }
		return lists, cnt, nil
	}
	return nil, 0, err
}


func UpdateWxAppCfgByAppId(m *WxAppCfg, fields ...string) error {
	o := models.GetDefaultDB()
	v := WxAppCfg{StoreId: m.StoreId, AppId: m.AppId, Name: m.Name}
	if err := o.Read(&v, "StoreId", "AppId", "Name"); err == nil {
		m.WxAppCfgId = v.WxAppCfgId
	    if _, err = o.Update(m, fields...); err != nil {
		    return err
		}
	}else{
	    return err
	}
	return nil
}

func DeleteWxAppCfgByAppId(appId, name string) (err error) {
	o := models.GetDefaultDB()
	v := WxAppCfg{AppId:appId, Name:name}
	if err = o.Read(&v, "AppId", "Name"); err == nil {
		if _, err = o.Delete(&v); err == nil {
			return nil
		}
	}
	return
}
